package com.alon.spring01.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring01
 * @description: jwt测试
 * @author: yulongguang
 * @create: 2019-07-31 17:01
 **/
public class JwtHelperUtils {
    private static final String SECRET = "TESTSECRET!2018";

    /**
     * 生成Token
     * @return
     * @throws Exception
     */
    public static String createToken() throws Exception {

        Calendar c = Calendar.getInstance();
        Date date = c.getTime();

        c.add(Calendar.MINUTE,1);
        Date expires = c.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)
                .withClaim("name", "tank")
                .withClaim("operator","joseph")
                .withExpiresAt(expires)
                .withIssuedAt(date)
                .sign(Algorithm.HMAC256(SECRET));

        return token;
    }

    /**
     * 校验token
     * @param token
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Map<String, Claim> verifyToken(String token) throws UnsupportedEncodingException {
        DecodedJWT jwt  = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return jwt.getClaims();
    }
    public static void main(String[] args) throws Exception {
        String token = createToken();
        System.out.println("Token:" + token);

        Map<String, Claim> claims = verifyToken(token);
        System.out.println(claims.get("name").asString());
        System.out.println(claims.get("operator").asString());

        String expireToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJuaW5naGFvLm5ldCIsImV4cCI6IjE0Mzg5NTU0NDUiLCJuYW1lIjoid2FuZ2hhbyIsImFkbWluIjp0cnVlfQ.SwyHTEx_RQppr97g4J5lKXtabJecpejuef8AqKYMAJc";
        Map<String, Claim> expireTokenClaim = verifyToken(expireToken);
        System.out.println(expireTokenClaim.get("name").asString());
        System.out.println(expireTokenClaim.get("operator").asString());


    }
}
